var buildDownload = function(imageFile) {
	return $('<tr id="'
			+ imageFile.image.imageID
			+ '"><td>'
			+ '<a href="'
			+ imageFile.downloadURL
			+ '">'
			+ imageFile.name
			+ '</a>'
			+ '<\/td><td>'
			+ imageFile.size
			+ '<\/td><td>'
			+ '<img id="delDoc" class="del" src="./images/del.png" onclick="deleteAttachment('
			+ imageFile.image.imageID + ')"></img></td><\/tr>');
};

var buildUpload = function(files, index) {
	return $('<tr><td>' + files[index].name + '<\/td>'
			+ '<td class="file_upload_progress"><div><\/div><\/td>'
			+ '<td class="file_upload_cancel">'
			+ '<button class="ui-state-default ui-corner-all" title="Cancel">'
			+ '<span class="ui-icon ui-icon-cancel">Cancel<\/span>'
			+ '<\/button><\/td><\/tr>');
}

function loadDownload(files) {
	var htmlRows = "";
	$(files)
			.each(
					function(index, imageFile) {
						htmlRows = htmlRows
								+ ('<tr id="'
										+ imageFile.image.imageID
										+ '"><td>'
										+ '<a href="'
										+ imageFile.downloadURL
										+ '">'
										+ imageFile.name
										+ '</a>'
										+ '<\/td><td>'
										+ imageFile.size
										+ '<\/td><td>'
										+ '<img id="delDoc" class="del" src="./images/del.png" onclick="deleteAttachment('
										+ imageFile.image.imageID + ')"></img></td><\/tr>');
					});
	return htmlRows;
}

function deleteAttachment(imageId) {
	$.getJSON("/eslserver/DeleteAttachment.do?imageID=" + imageId, function(
			data) {
		$('tr#' + imageId).remove();
	});
}

function initFileUpload(suffix, eslID) {
	var fileUploadUI = $('#file_upload').fileUploadUI( {
		namespace : 'file_upload_' + suffix,
		fileInputFilter : '#file_' + suffix,
		dropZone : $('#drop_zone_' + suffix),
		uploadTable : $('#files_' + suffix),
		downloadTable : $('#files_' + suffix),
		buildUploadRow : buildUpload,
		buildDownloadRow : buildDownload
	});

	if (suffix == 1) {
		$.getJSON("/eslserver/LoadImageServlet.do?eslID=" + eslID, function(
				data) {
			$("#files_1").attr("innerHTML", loadDownload(data));
		});
	}
}